<?php

namespace app\web\controller;
use app\commons\model\Sale as SaleModel;
use app\commons\model\ActivityVideo;
use redis\Redis;
use think\exception\ValidateException;
use collar\CollarBag;

class Sale
{
    /**
     * 获取活动详情，返回用户领取的次数
     * @param SaleModel $saleModel
     * @return \think\response\Jsonp
     */
    public function index(SaleModel $saleModel){
        $mac_info = session('mac_info');
        if(!$mac_info) return jsonp_error(422,'请重新扫码！');
        if(!Redis::redis()->get($mac_info->redis_name)) return jsonp_error(422,'操作超时，请重新扫码设备二维码！');
        $mac_id = $mac_info->mac_id;
        //取一个没有使用过的视频
//        $video = ActivityVideo::where(['status'=>1,'is_download_status'=>1,'is_use'=>0])->field(['path','id','sale_id','title','yun_url'])->find();
        $video = ActivityVideo::where('id','in','247,248,249')->orderRaw('rand()')->field(['path','id','sale_id','title','yun_url'])->find();
        if(!$video) return jsonp_error(422,'活动太火爆了，请稍后再试！');
        $data = $saleModel->where('id',$video['sale_id'])->field(['content','id','replace','starttime','endtime','poi_address','pic'])->find();
        $video['path'] = images_url($video['path']);
        if(isset($video['yun_url']) && !empty($video['yun_url'])){
            $video['path'] = $video['yun_url'];
        }
        $data['video'] = $video;
        $data['pic'] = images_url($data['pic']);
        //判断用户是否可以领取
        $data['is_receive'] = true;
        $userData = CollarBag::syncUser(session('user'),$mac_id);
        if(!isset($userData['finish_task_num']) || !isset($userData['global_task_num'])) throw new ValidateException('机器状态异常！');
        if($userData['finish_task_num'] >= $userData['global_task_num']) $data['is_receive'] = false;
        $data['finish_task_num'] = $userData['finish_task_num'] ?? 0;
        $data['global_task_num'] = $userData['global_task_num'] ?? 3;
        return jsonp($data);
    }
}